#include "rttI2C.h"

#include <usdev/i2c.h>
#include <usdev/i2c-dev.h>

using namespace NXMFC;

int rttI2C::writeb(uint8_t id, uint8_t addr, uint8_t val)
{
    int ret;
    struct rt_i2c_msg msg[1];
    struct i2c_rdwr_ioctl_data rw;
    uint8_t buf[2];

    buf[0] = addr;
    buf[1] = val;

    msg[0].addr = id;
    msg[0].flags = RT_I2C_WR;
    msg[0].buf = buf;
    msg[0].len = 2;

    rw.msgs = msg;
    rw.nmsgs = 1;

    ret = ioctl(I2C_RDWR, &rw);

    return ret;
}

int rttI2C::readb(uint8_t id, uint8_t addr, uint8_t &val)
{
    return readv(id, addr, &val, 1);
}

int rttI2C::readv(uint8_t id, uint8_t addr, uint8_t *val, uint16_t len)
{
    int ret;
    struct rt_i2c_msg msg[2];
    struct i2c_rdwr_ioctl_data rw;

    msg[0].addr = id;
    msg[0].flags = RT_I2C_WR;
    msg[0].buf = &addr;
    msg[0].len = 1;

    msg[1].addr = id;
    msg[1].flags = RT_I2C_RD;
    msg[1].buf = val;
    msg[1].len = len;

    rw.msgs = msg;
    rw.nmsgs = 2;

    ret = ioctl(I2C_RDWR, &rw);

    return ret;
}
